//
//  EditeAddressViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/17.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "EditeAddressViewController.h"
#import <MBProgressHUD.h>
#import <Masonry.h>
#import "VervifyPhone.h"
#import "Address.h"
#import "AreaPick.h"
#import "BLHeader.h"
#import "UpdateNet.h"

@interface EditeAddressViewController () <AreaPickDelegate>
@property (weak, nonatomic) IBOutlet UITextField *contactNameField;
@property (weak, nonatomic) IBOutlet UITextField *contactTelFeild;
@property (weak, nonatomic) IBOutlet UILabel *areaLabel;
@property (weak, nonatomic) IBOutlet UITextView *detailText;
@property (weak, nonatomic) IBOutlet UIView *deleAddressView;
@property (weak, nonatomic) IBOutlet UIView *approveAddressView;
@property (weak, nonatomic) IBOutlet UIButton *selectApproveAddressBtn;
@property (weak, nonatomic) IBOutlet UIView *areaView;
@property (nonatomic, strong) AreaPick *areaPick;
@property (nonatomic, strong) NSString *provice;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *area;
@property (nonatomic, strong) NSString *detail;
@property (nonatomic, assign) BOOL isApproveAddress;//是不是默认地址


@end

@implementation EditeAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"编辑地址";
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(commitUpdateAddress)];
    [right setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:kAppThemeColor ,NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    
    __weak typeof (self) weakSelf = self;
    if(self.isEdit) {
        // 判断是不是默认地址 如果是默认地址 就把approveAddressView 隐藏
        BOOL selected = [@"是" isEqualToString:self.address.isApprove] ?  YES : NO;
        if (selected) {
            [self.approveAddressView setHidden:selected];
            [self.deleAddressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.equalTo(weakSelf.approveAddressView);
            }];
        }else {
            [self.deleAddressView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(weakSelf.approveAddressView.mas_bottom).with.offset(15);
                make.size.equalTo(weakSelf.approveAddressView);
            }];
        }
    }else {
        [self.deleAddressView setHidden:YES];
        [self.deleAddressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.approveAddressView.mas_bottom).with.offset(15);
            make.size.equalTo(weakSelf.approveAddressView);
        }];
    }
    
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(deleteAddressEvent)];
    [self.deleAddressView addGestureRecognizer:tapRecognizer];
    
    UITapGestureRecognizer *areaRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(choiceArea)];
    [self.areaView addGestureRecognizer:areaRecognizer];
    
    UITapGestureRecognizer *hide = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [self.view addGestureRecognizer:hide];
    
    self.areaPick = [AreaPick areaPick];
    self.areaPick.frame = [UIScreen mainScreen].bounds;
    self.areaPick.delegate = self;
    
    if(self.address) {
        self.contactNameField.text = self.address.name;
        self.contactTelFeild.text = self.address.tel;
        self.areaLabel.text = self.address.areaDetail;
        self.detailText.text = self.address.detail;
        [self.selectApproveAddressBtn setSelected:[@"是" isEqualToString:self.address.isApprove] ? YES : NO];
    }
    
    if (_mustApprove) {
        [self.selectApproveAddressBtn setSelected:YES];
    }
    
    if([self.areaLabel.text length] == 0) {
        self.areaLabel.text = @"请选择";
        self.areaLabel.textColor = [UIColor grayColor];
    }else {
        self.areaLabel.textColor = [UIColor blackColor];
    }
}

- (void)hideKeyBoard {
    [self.view endEditing:YES];
}

- (void)choiceArea {
    [self.view endEditing:YES];
    [[[UIApplication sharedApplication] delegate].window addSubview:self.areaPick];
}


- (void)deleteAddressEvent {
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定要删除该地址吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
        [UpdateNet deleteAddress:self.address.addrNo completer:^(id resultObject, NSError *error) {
            hud.mode = MBProgressHUDModeText;
            if(error) {
                hud.label.text = [error localizedDescription];
                [hud hideAnimated:YES afterDelay:2];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:DELETEADDRESSNOTIFICATION object:self.address];
        }];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (IBAction)seletctApproveAddressEvent:(UIButton *)sender {
    if (self.mustApprove) {
        [sender setSelected:YES];
        return;
    }
    
    if (sender.isSelected) {
        [sender setSelected:NO];
        self.isApproveAddress = NO;
    }else {
        [sender setSelected:YES];
        self.isApproveAddress = YES;
    }
}


#pragma mark 保存点击事件
- (void)commitUpdateAddress {
    [self.view endEditing:YES];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    NSString *tel = self.contactTelFeild.text;
    if ([tel isEqualToString:@""]) {
        hud.label.text = @"请输入注册手机号码";
        [hud hideAnimated:YES afterDelay:2];
        return;
    }
    if (tel.length != 11 || ![VervifyPhone vervifyTellphoneNumber:tel]) {
        [hud hideAnimated:YES afterDelay:2];
        hud.label.text = @"手机号码格式不正确";
        return;
    }
    
    NSString *name = self.contactNameField.text;
    if([name isEqualToString:@""]) {
        hud.label.text = @"请输入联系人";
        [hud hideAnimated:YES afterDelay:2];
        return;
    }
    
    NSString *town = self.areaLabel.text;
    if([town isEqualToString:@"请选择"]) {
        hud.label.text = @"请选择所在地区";
        [hud hideAnimated:YES afterDelay:2];
        return;
    }
    
    self.detail = self.detailText.text;
    if(self.detail.length == 0) {
        hud.label.text = @"请输入详细地址";
        [hud hideAnimated:YES afterDelay:2];
        return;
    }
    hud.mode = MBProgressHUDModeIndeterminate;
    __weak typeof (self) weakSelf = self;
    NSString *userTel = [[NSUserDefaults standardUserDefaults] objectForKey:USERTEL];
      if(self.isEdit) { // 修改地址
          NSString *strNO = self.address.addrNo;
          if(!self.provice || [self.provice length] == 0) {
              self.provice = self.address.provice;
              self.city = self.address.city;
              self.area = self.address.area;
          }
          NSDictionary *dic = @{@"addrNo":strNO, @"linkName":name, @"userAddr":self.provice, @"userAddr2":self.city, @"userAddr3":self.area, @"userAddr4":self.detail, @"phoneNumber":tel, @"defaultAddr": self.isApproveAddress ? @"是" : @"否"};

         [UpdateNet updateAddress:dic completer:^(id resultObject, NSError *error) {
             hud.mode = MBProgressHUDModeText;
             if(error) {
                 [hud hideAnimated:YES afterDelay:2];
                 return;
             }
             hud.label.text = @"修改成功！";
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                 [hud hideAnimated:YES];
                 [weakSelf.navigationController popViewControllerAnimated:YES];
             });
             [[NSNotificationCenter defaultCenter] postNotificationName:UPDATEADDRESSNOTIFICATION object:resultObject];
        }];
    }else {// 新建地址
        NSDictionary *dic = @{@"userTel":userTel, @"linkName":name, @"userAddr":self.provice, @"userAddr2":self.city, @"userAddr3":self.area, @"userAddr4":self.detail, @"phoneNumber":tel, @"defaultAddr": self.isApproveAddress ? @"是" : @"否"};
        [UpdateNet addNewAddress:dic completer:^(id resultObject, NSError *error) {
            hud.mode = MBProgressHUDModeText;
            if(error) {
                hud.label.text = @"添加失败！";
                [hud hideAnimated:YES afterDelay:2];
                return;
            }
            hud.label.text = @"添加成功！";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            [[NSNotificationCenter defaultCenter] postNotificationName:ADDADDRESSNOTIFICATION object:resultObject];
        }];
    }
}

- (void)cancelChoice {
    [self.areaPick removeFromSuperview];
}

- (void)commitArea:(NSString *)provice city:(NSString *)city area:(NSString *)area {
    [self.areaPick removeFromSuperview];
    self.provice = provice;
    self.city = city;
    self.area = area;
    NSString *address = [NSString stringWithFormat:@"%@%@%@", self.provice, self.city, self.area];
    self.areaLabel.text = address;
    self.areaLabel.textColor = [UIColor blackColor];
}
@end
